package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.InformationType;
import me.xue.communityhealth.service.InformationTypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class InformationTypeController {

    private final InformationTypeService service;

    public InformationTypeController(InformationTypeService service) {
        this.service = service;
    }

    @GetMapping("/informationType/add")
    public String addPage(Model model) {
        model.addAttribute("informationType", new InformationType());
        return "information_type_edit";
    }

    @PostMapping("/informationType")
    public String add(InformationType informationType) {
        int inserted = service.save(informationType);
        if (inserted == 1) {
            return "redirect:/informationTypes";
        }
        return "information_type_edit";
    }

    @GetMapping("/informationType/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("informationType", service.findOne(id));
        return "information_type_edit";
    }

    @PutMapping("/informationType")
    public String update(InformationType informationType) {
        int updated = service.update(informationType);
        if (updated == 1) {
            return "redirect:/informationTypes";
        }
        return "information_type_edit";
    }

    @DeleteMapping("/informationType/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        int deleted = service.delete(id);
        if (deleted == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/informationTypes")
    public String all(Model model) {
        List<InformationType> informationTypes = service.findAll();
        model.addAttribute("informationTypes", informationTypes);
        return "information_types";
    }


}
